#!/bin/bash

# shellcheck source=start-utils
. "$(dirname "$0")/start-utils"

: "${SYNC_SKIP_NEWER_IN_DESTINATION:=${PLUGINS_SYNC_UPDATE:-true}}"
: "${REPLACE_ENV_DURING_SYNC:=true}"
: "${REPLACE_ENV_SUFFIXES:=yml,yaml,txt,cfg,conf,properties,hjson,json,tml,toml}"
: "${REPLACE_ENV_VARIABLE_PREFIX=${ENV_VARIABLE_PREFIX:-CFG_}}"
: "${REPLACE_ENV_VARIABLES_EXCLUDES:=}"
: "${REPLACE_ENV_VARIABLES_EXCLUDE_PATHS:=}"
: "${DEBUG:=false}"
: "${MODS_OUT_DIR:=/data/mods}"
: "${PLUGINS_OUT_DIR:=/data/plugins}"

set -e
isDebugging && set -x

if isTrue "${SYNC_SKIP_NEWER_IN_DESTINATION}"; then
  updateArg="--skip-newer-in-destination"
fi

if isTrue "${REPLACE_ENV_DURING_SYNC}"; then
  subcommand=sync-and-interpolate
else
  subcommand=sync
fi

function mc-image-helper-mounts(){
  mc-image-helper \
    ${subcommand} $updateArg \
    --replace-env-file-suffixes="${REPLACE_ENV_SUFFIXES}" \
    --replace-env-excludes="${REPLACE_ENV_VARIABLES_EXCLUDES}" \
    --replace-env-exclude-paths="${REPLACE_ENV_VARIABLES_EXCLUDE_PATHS}" \
    --replace-env-prefix="${REPLACE_ENV_VARIABLE_PREFIX}" "$@"
}

: "${COPY_PLUGINS_SRC:="/plugins"}"
: "${COPY_PLUGINS_DEST:=${PLUGINS_OUT_DIR}}"

if usesPlugins; then
  mkdir -p "${COPY_PLUGINS_DEST}"
  log "Copying any plugins from ${COPY_PLUGINS_SRC} to ${COPY_PLUGINS_DEST}"
  mc-image-helper-mounts "${COPY_PLUGINS_SRC}" "${COPY_PLUGINS_DEST}"
fi

: "${COPY_MODS_SRC:="/mods"}"
: "${COPY_MODS_DEST:=${MODS_OUT_DIR}}"

if usesMods; then
  log "Copying any mods from ${COPY_MODS_SRC} to ${COPY_MODS_DEST}"
  mc-image-helper-mounts "${COPY_MODS_SRC}" "${COPY_MODS_DEST}"
fi

: "${COPY_CONFIG_SRC:="/config"}"
: "${COPY_CONFIG_DEST:="/data/config"}"

log "Copying any configs from ${COPY_CONFIG_SRC} to ${COPY_CONFIG_DEST}"
mc-image-helper-mounts "${COPY_CONFIG_SRC}" "${COPY_CONFIG_DEST}"

exec "$(dirname "$0")/start-setupServerProperties" "$@"
